import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:8080',  // 直接使用完整的后端地址
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: false // 禁用跨域请求时发送Cookie
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      // 确保token格式正确
      config.headers['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`
    }
    
    // 添加跨域请求头
    config.headers['Access-Control-Allow-Origin'] = '*'
    config.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    config.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization'
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 获取响应数据
    const res = response.data

    // 处理登录接口的特殊响应
    if (response.config.url.includes('/login')) {
      if (res.data?.token) {
        // 存储token到localStorage
        localStorage.setItem('token', `Bearer ${res.data.token}`)
        // 存储用户信息
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        return res.data
      }
    }

    // 处理简单数据
    if (typeof res === 'string' || typeof res === 'number') {
      return res
    }

    // 处理数组数据
    if (Array.isArray(res)) {
      return res
    }

    // 处理标准响应
    if (res.code === 200 || res.data) {
      return res.data || res
    }

    // 处理错误
    const errorMsg = res.msg || res.message || '请求失败'
    ElMessage.error(errorMsg)
    return Promise.reject(new Error(errorMsg))
  },
  error => {
    // 处理网络错误
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          // 清除所有localStorage中的认证信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(error.response.data?.msg || '网络错误')
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请稍后重试')
    } else {
      ElMessage.error('网络连接失败')
    }
    return Promise.reject(error)
  }
)

export const userApi = {
  // 用户登录
  login: (data) => {
    return request.post('/user/login', data)
  },
  // 测试管理员权限
  testAdmin: (username) => {
    return request.post('/user/testAdmin', null, { params: { username } })
  },
  // 测试访客权限
  testGuest: (username) => {
    return request.get('/user/testGuest', { params: { username } })
  },
  // 登出
  logout: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/login')
  }
}

export const sensorApi = {
  // 获取传感器最新数据
  getLatestData: () => {
    return request.get('/sensors/latest')
  },
  
  // 获取传感器历史数据
  getHistoricalData: (sensorType, page = 0, size = 10) => {
    return request.get(`/sensors/history/${sensorType}`, {
      params: { page, size }
    })
  },

  // 获取传感器数据
  fetchSensorData: (boxNo, sensorIds) => {
    return request.post('/sensors/fetch', null, {
      params: { boxNo, sensorIds }
    })
  }
}

export const cameraApi = {
  // 获取萤石云token
  getToken: () => {
    return request.get('/camera/getToken')
  },
  
  // 获取历史数据
  getHistoricalData: () => {
    return request.get('/camera/historical-data')
  },
  
  // 获取最新数据
  getLatestData: () => {
    return request.get('/camera/latest-data')
  },
  
  // 截图
  capturePhoto: (deviceSerial) => {
    return request.post('/camera/capture', { deviceSerial })
  }
} 